<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>WebSocket连接</span>
          </div>
          <el-input v-model="url" type="text" style="width: 60%" /> &nbsp; &nbsp;
          <el-button @click="join" type="primary">连接</el-button>
          <el-button @click="exit" type="danger">断开</el-button>
          <el-button @click="getOnlineUsers" type="info">获取在线用户</el-button>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>发送消息</span>
          </div>
          <el-form>
            <el-form-item label="消息类型">
              <el-radio-group v-model="messageType">
                <el-radio label="all">全体消息</el-radio>
                <el-radio label="user">私聊消息</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="接收用户" v-if="messageType === 'user'">
              <el-select v-model="selectedUser" placeholder="请选择接收用户" style="width: 100%">
                <el-option
                  v-for="user in onlineUsers"
                  :key="user.id"
                  :label="user.userName + ' (' + user.userId + ')' + (user.id === mySessionId ? ' (自己)' : '')"
                  :value="user.id"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="消息内容">
              <el-input type="textarea" v-model="message" :rows="6" placeholder="请输入消息内容"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="send">发送消息</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>消息记录</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="clearMessages">清空</el-button>
          </div>
          <div class="message-container">
            <div v-for="(msg, index) in messages" :key="index" class="message-item">
              <div class="message-time">{{ msg.time }}</div>
              <div class="message-content">
                <template v-if="msg.from">
                  <span style="color: #409EFF; margin-right: 5px;">{{ msg.from.userName || msg.from.userId }}</span>
                </template>
                {{ msg.content }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>在线用户列表</span>
            <span style="margin-left: 10px; color: #909399; font-size: 13px">
              (共 {{ onlineUsers.length }} 人)
            </span>
          </div>
          <el-table :data="onlineUsers" border style="width: 100%">
            <el-table-column prop="id" label="会话ID" width="280"></el-table-column>
            <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
            <el-table-column prop="userName" label="用户名" width="120"></el-table-column>
            <el-table-column label="状态" width="100">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.id === mySessionId">自己</el-tag>
                <el-tag type="info" v-else>在线</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="chatWithUser(scope.row)"
                  :disabled="scope.row.id === mySessionId"
                >
                  发送消息
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import store from '../store'

export default {

  data() {
    return {
      url: "ws://127.0.0.1:8080/websocket/message",
      message: "",
      text_content: "",
      ws: null,
      messageType: "all", // 默认为全体消息
      selectedUser: "", // 选中的用户
      onlineUsers: [], // 在线用户列表
      mySessionId: "", // 自己的会话ID
      messages: [], // 消息记录
    };
  },
  created() {
    console.log('userId',store.getters.id)
  },
  methods: {
    join() {
      // 从store获取当前用户ID和用户名
      const userId = store.getters.id;
      const userName = store.getters.name;

      // 添加userId和userName参数到WebSocket URL
      const wsuri = `${this.url}?userId=${userId}&userName=${encodeURIComponent(userName)}`;
      this.ws = new WebSocket(wsuri);
      const self = this;

      this.ws.onopen = function (event) {
        self.addMessage("系统消息", "已经打开连接!");
        // 连接成功后获取在线用户列表
        self.getOnlineUsers();
      };

      this.ws.onmessage = function (event) {
        console.log(event.data);

        // 尝试解析消息
        try {
          const data = JSON.parse(event.data);

          if (data.type === "userList") {
            self.onlineUsers = data.users;
            self.addMessage("系统消息", "获取到在线用户列表");
          } else if (data.type === "connect") {
            // 如果是连接成功消息，记录自己的会话ID
            self.mySessionId = data.sessionId;
            self.addMessage("系统消息", "连接成功，会话ID: " + data.sessionId);
          } else if (data.type === "message" || data.message) {
            // 处理聊天消息
            self.addMessage("收到消息", data.message || event.data, data.from, data.to);
          } else if (data.type === "userJoin") {
            // 用户加入消息
            self.addMessage("系统消息", `用户 ${data.userName || data.userId || data.sessionId} 加入聊天`);
            // 更新用户列表
            self.getOnlineUsers();
          } else if (data.type === "userLeave") {
            // 用户离开消息
            self.addMessage("系统消息", `用户 ${data.userName || data.userId || data.sessionId} 离开聊天`);
            // 更新用户列表
            self.getOnlineUsers();
          } else {
            // 其他类型的消息
            self.addMessage("收到消息", event.data);
          }
        } catch (e) {
          // 不是JSON格式，当作普通消息处理
          self.addMessage("收到消息", event.data);
        }
      };

      this.ws.onclose = function (event) {
        self.addMessage("系统消息", "已经关闭连接!");
        self.onlineUsers = []; // 清空在线用户列表
        self.mySessionId = ""; // 清空会话ID
      };
    },

    exit() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },

    send() {
      if (!this.ws) {
        this.$message.error("未连接到服务器");
        return;
      }

      if (!this.message.trim()) {
        this.$message.warning("消息内容不能为空");
        return;
      }

      let messageObj = {
        type: this.messageType,
        message: this.message
      };

      if (this.messageType === "user") {
        if (!this.selectedUser) {
          this.$message.warning("请选择接收用户");
          return;
        }
        messageObj.to = this.selectedUser;
      }

      this.ws.send(JSON.stringify(messageObj));
      this.addMessage("发送消息", `[${this.messageType === 'all' ? '全体消息' : '私聊消息'}] ${this.message}`);
      this.message = ""; // 清空消息输入框
    },

    getOnlineUsers() {
      if (!this.ws) {
        this.$message.error("未连接到服务器");
        return;
      }

      // 发送获取在线用户列表的请求
      // 注意：这里假设后端支持这种请求，实际上可能需要修改后端代码
      this.ws.send(JSON.stringify({
        type: "getUsers"
      }));
    },

    chatWithUser(user) {
      this.messageType = "user";
      this.selectedUser = user.id;
      this.$message.success(`已选择与用户 ${user.id} 聊天`);
    },

    addMessage(type, content, from = null, to = null) {
      const now = new Date();
      const timeStr = now.toLocaleTimeString();

      // 尝试解析JSON消息
      let parsedContent = content;
      let messageObj = {
        time: timeStr,
        type: type,
        content: content,
        from: from,
        to: to
      };

      try {
        if (typeof content === 'string') {
          const jsonData = JSON.parse(content);
          if (jsonData.message) {
            messageObj.content = jsonData.message;
          }
          if (jsonData.from) {
            messageObj.from = jsonData.from;
          }
          if (jsonData.to) {
            messageObj.to = jsonData.to;
          }
          if (jsonData.type) {
            messageObj.type = jsonData.type;
          }
        }
      } catch (e) {
        // 不是JSON格式，使用原始内容
      }

      this.messages.push(messageObj);

      // 保持消息记录不超过100条
      if (this.messages.length > 100) {
        this.messages.shift();
      }
    },

    clearMessages() {
      this.messages = [];
    }
  }
};
</script>

<style scoped>
.message-container {
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.message-item {
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.message-content {
  word-break: break-all;
}
</style>
